﻿using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Events.Bus.Entities;
using Abp.Events.Bus.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FwProject.Core.SettlementInfoModel;
using FwProject.Core.Distribution;
using Abp.Runtime.Caching;

using FwProject.Restaurant;
using FwProject.Users;
using Abp.RemoteEventBus;
using Abp.ObjectMapping;
using FwProject.Distribution.Dto;
using FwProject.Restaurant.Dto;
using FwProject.PublicService.JPush;
using FwProject.BackGround;
using FwProject.BackGround.DistributionEnter;
using Abp.BackgroundJobs;
using FwProject.Comm;
using Abp.Logging;
using Castle.Core.Logging;
using Abp;
using FwProject.EventBusData;
using Abp.Domain.Uow;
using FwProject.Core.Restaurant;
using FwProject.Distribution;

namespace FwProject.Application.EventHandl
{
    public class DistributionInfoLogInfoHandle :
        IEventHandler<CreatedDistributionEventData>,
        IEventHandler<EditDistributionEventData>,
        IEventHandler<CreatedDistributionDetailsEventData>,
    ITransientDependency
    {
        public readonly ICacheManager _catchmanager;
        public readonly IJPushAppservice _jPushAppservice;

        private readonly IRepository<DistributionInfo, Guid> _repositoryDistributionInfo;
        private readonly IRepository<DistributionInfoDetails, Guid> _repositoryDistributionInfoDetails;
        private readonly IRepository<RestaurantInfo, Guid> _repositoryRestaurantInfo;
        private readonly IRepository<DistributionHistory, Guid> _repositoryDistributionHistory;
        public ILogger _logger { get; set; }

        public IGuidGenerator _guid { get; set; }
        public IObjectMapper _map { get; set; }//缓存对象
        public IRemoteEventBus remoteEventBus { get; set; }//缓存对象

        private readonly IUnitOfWorkManager _unitOfWorkManager;

        public DistributionInfoLogInfoHandle(ICacheManager catchmanager, IJPushAppservice jPushAppservice,
                                       IRepository<DistributionInfoDetails, Guid> repositoryDistributionInfoDetails,
                                     IRepository<DistributionInfo, Guid> repositoryDistributionInfo,
                                      IRepository<RestaurantInfo, Guid> repositoryRestaurantInfo,
                                       IRepository<DistributionHistory, Guid> repositoryDistributionHistory,
                                       IUnitOfWorkManager unitOfWorkManager
            )
        {
            _repositoryDistributionHistory = repositoryDistributionHistory;
            _guid = SequentialGuidGenerator.Instance;
            _repositoryRestaurantInfo = repositoryRestaurantInfo;
            _repositoryDistributionInfo = repositoryDistributionInfo;
            _repositoryDistributionInfoDetails = repositoryDistributionInfoDetails;
            _logger = NullLogger.Instance;
            _catchmanager = catchmanager;
            _jPushAppservice = jPushAppservice;
            _map = NullObjectMapper.Instance;
            remoteEventBus = NullRemoteEventBus.Instance;
            _unitOfWorkManager = unitOfWorkManager;
        }
        /// <summary>
        /// 添加配送
        /// </summary>
        /// <param name="eventData"></param>

        [UnitOfWork]
        public void HandleEvent(CreatedDistributionEventData eventData)
        {
            using (var unitOfWork = _unitOfWorkManager.Begin())
            {
                var model = _repositoryDistributionInfoDetails.GetAll().Where(o => o.Restaurantid == eventData.RestaurantId);
                var restaurant = _repositoryRestaurantInfo.Get(eventData.RestaurantId);
                var stock = restaurant.Stock + model.Sum(o => o.Distributioncount) + model.Sum(o => o.Givecount) - model.Sum(o => o.Recoverycount);

                DistributionHistory his = new DistributionHistory();
                his.Id = _guid.Create();
                his.DistributionId = eventData.Id;
                his.OperatingUserId = eventData.UserId;
                his.Record = $"新增配送：【餐厅】为{restaurant.RestaurantName},【店存(实存)】为{stock}";
                _repositoryDistributionHistory.Insert(his);

                unitOfWork.Complete();
            }

        }

        /// <summary>
        /// 配送型号
        /// </summary>
        /// <param name="eventData">Event data.</param>
        [UnitOfWork]
        public void HandleEvent(CreatedDistributionDetailsEventData eventData)
        {
            using (var unitOfWork = _unitOfWorkManager.Begin())
            {
                string msg = $"新增货品【{eventData.EventDataDistributionInfoDetails.TypeNumberName}】：";
                if (eventData.EventDataDistributionInfoDetails.Distributioncount > 0)
                {
                    msg += $"【配送箱数】为{eventData.EventDataDistributionInfoDetails.Distributioncount },";
                }
                if (eventData.EventDataDistributionInfoDetails.Recoverycount > 0)
                {
                    msg += $"【回收箱数】为{eventData.EventDataDistributionInfoDetails.Recoverycount },";
                }
                if (eventData.EventDataDistributionInfoDetails.Givecount > 0)
                {
                    msg += $"【赠送箱数】为{eventData.EventDataDistributionInfoDetails.Givecount },";
                }
                if (eventData.EventDataDistributionInfoDetails.Exchangegoodscount > 0)
                {
                    msg += $"【换货箱数】为{eventData.EventDataDistributionInfoDetails.Exchangegoodscount },";
                }
                if (eventData.EventDataDistributionInfoDetails.Damagecount > 0)
                {
                    msg += $"【折损套数】为{eventData.EventDataDistributionInfoDetails.Damagecount },";
                }
                if (eventData.EventDataDistributionInfoDetails.Backboxcount > 0)
                {
                    msg += $"【退回箱数】为{eventData.EventDataDistributionInfoDetails.Backboxcount },";
                }
                if (eventData.EventDataDistributionInfoDetails.Backnumbercount > 0)
                {
                    msg += $"【退回套数】为{eventData.EventDataDistributionInfoDetails.Backnumbercount },";
                }
                msg += $"【单价】为{eventData.EventDataDistributionInfoDetails.TypeNumberPrice}";

                DistributionHistory his = new DistributionHistory();
                his.Id = _guid.Create();
                his.DistributionId = eventData.Id;
                his.OperatingUserId = eventData.UserId;
                his.Record = msg;
                _repositoryDistributionHistory.Insert(his);

                var model = _repositoryDistributionInfoDetails.GetAll().Where(o => o.Restaurantid == eventData.RestaurantId);
                var restaurant = _repositoryRestaurantInfo.Get(eventData.RestaurantId);
                var stock = restaurant.Stock + model.Sum(o => o.Distributioncount) + model.Sum(o => o.Givecount) - model.Sum(o => o.Recoverycount);

                string record = $"【店存(实存)】改为{stock}";
                DistributionHistory h = new DistributionHistory();
                h.Id = _guid.Create();
                h.DistributionId = eventData.Id;
                h.OperatingUserId = eventData.UserId;
                h.Record = record;
                _repositoryDistributionHistory.Insert(h);

                unitOfWork.Complete();
            }

        }
        /// <summary>
        /// 修改型号
        /// </summary>
        /// <param name="eventData"></param>
        [UnitOfWork]
        public void HandleEvent(EditDistributionEventData eventData)
        {
            using (var unitOfWork = _unitOfWorkManager.Begin())
            {
                bool flag = false;
                string msg = $"货品【{eventData.EventNewDataDistributionInfoDetails.TypeNumberName}】修改明细：";
                if (eventData.EventOldDataDistributionInfoDetails.Distributioncount != eventData.EventNewDataDistributionInfoDetails.Distributioncount)
                {
                    msg += $"【配送箱数】由{eventData.EventOldDataDistributionInfoDetails.Distributioncount }改为{ eventData.EventNewDataDistributionInfoDetails.Distributioncount}，";
                    flag = true;
                }
                if (eventData.EventOldDataDistributionInfoDetails.Recoverycount != eventData.EventNewDataDistributionInfoDetails.Recoverycount)
                {
                    msg += $"【回收箱数】由{eventData.EventOldDataDistributionInfoDetails.Recoverycount }改为{ eventData.EventNewDataDistributionInfoDetails.Recoverycount}，";
                    flag = true;
                }
                if (eventData.EventOldDataDistributionInfoDetails.Givecount != eventData.EventNewDataDistributionInfoDetails.Givecount)
                {
                    msg += $"【赠送箱数】由{eventData.EventOldDataDistributionInfoDetails.Givecount }改为{ eventData.EventNewDataDistributionInfoDetails.Givecount}，";
                    flag = true;
                }
                if (eventData.EventOldDataDistributionInfoDetails.Exchangegoodscount != eventData.EventNewDataDistributionInfoDetails.Exchangegoodscount)
                {
                    msg += $"【换货箱数】由{eventData.EventOldDataDistributionInfoDetails.Exchangegoodscount }改为{ eventData.EventNewDataDistributionInfoDetails.Exchangegoodscount}";
                    flag = true;
                }
                if (eventData.EventOldDataDistributionInfoDetails.Damagecount != eventData.EventNewDataDistributionInfoDetails.Damagecount)
                {
                    msg += $"【折损套数】由{eventData.EventOldDataDistributionInfoDetails.Damagecount }改为{ eventData.EventNewDataDistributionInfoDetails.Damagecount}";
                    flag = true;
                }
                if (eventData.EventOldDataDistributionInfoDetails.Backboxcount != eventData.EventNewDataDistributionInfoDetails.Backboxcount)
                {
                    msg += $"【退回箱数】由{eventData.EventOldDataDistributionInfoDetails.Backboxcount }改为{ eventData.EventNewDataDistributionInfoDetails.Backboxcount}";
                    flag = true;
                }
                if (eventData.EventOldDataDistributionInfoDetails.Backnumbercount != eventData.EventNewDataDistributionInfoDetails.Backnumbercount)
                {
                    msg += $"【退回套数】由{eventData.EventOldDataDistributionInfoDetails.Backnumbercount }改为{ eventData.EventNewDataDistributionInfoDetails.Backnumbercount}";
                    flag = true;
                }
                if (flag)
                {
                    DistributionHistory his = new DistributionHistory();
                    his.Id = _guid.Create();
                    his.DistributionId = eventData.Id;
                    his.OperatingUserId = eventData.UserId;
                    his.Record = msg;
                    _repositoryDistributionHistory.Insert(his);

                    var model = _repositoryDistributionInfoDetails.GetAll().Where(o => o.Restaurantid == eventData.RestaurantId);
                    var restaurant = _repositoryRestaurantInfo.Get(eventData.RestaurantId);
                    var stock = restaurant.Stock + model.Sum(o => o.Distributioncount) + model.Sum(o => o.Givecount) - model.Sum(o => o.Recoverycount);

                    string record = $"【店存(实存)】改为{stock}";
                    DistributionHistory h = new DistributionHistory();
                    h.Id = _guid.Create();
                    h.DistributionId = eventData.Id;
                    h.OperatingUserId = eventData.UserId;
                    h.Record = record;
                    _repositoryDistributionHistory.Insert(h);
                }

                unitOfWork.Complete();
            }
        }
    }
}
